<!--
  Element Plus组件安全包装器
  @author Wu.Liang
  @date 2025-01-30
-->
<template>
  <div v-if="isReady" class="safe-element-wrapper">
    <slot />
  </div>
  <div v-else class="safe-element-wrapper-loading">
    <slot name="loading">
      <div class="loading-placeholder">
        <el-icon class="is-loading"><Loading /></el-icon>
        <span>组件加载中...</span>
      </div>
    </slot>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { Loading } from '@element-plus/icons-vue'
import { waitForDOMUpdate, isElementVisible, hasElementSize } from '@/utils/dom'

interface Props {
  delay?: number
  retryCount?: number
  retryDelay?: number
  selector?: string
}

const props = withDefaults(defineProps<Props>(), {
  delay: 100,
  retryCount: 3,
  retryDelay: 100,
  selector: ''
})

const isReady = ref(false)

/**
 * 检查组件是否准备就绪
 */
async function checkComponentReady(): Promise<boolean> {
  try {
    // 等待DOM更新
    await waitForDOMUpdate()
    
    // 如果有指定选择器，检查该元素
    if (props.selector) {
      const element = document.querySelector(props.selector)
      if (!element) return false
      
      return isElementVisible(element) && hasElementSize(element)
    }
    
    // 否则检查当前组件的根元素
    const rootElement = document.querySelector('.safe-element-wrapper')
    if (!rootElement) return false
    
    return isElementVisible(rootElement) && hasElementSize(rootElement)
  } catch (error) {
    console.warn('检查组件准备状态失败:', error)
    return false
  }
}

/**
 * 等待组件准备就绪
 */
async function waitForReady(): Promise<void> {
  // 初始延迟
  if (props.delay > 0) {
    await new Promise(resolve => setTimeout(resolve, props.delay))
  }
  
  // 重试机制
  for (let i = 0; i < props.retryCount; i++) {
    if (await checkComponentReady()) {
      isReady.value = true
      return
    }
    
    if (i < props.retryCount - 1) {
      await new Promise(resolve => setTimeout(resolve, props.retryDelay))
    }
  }
  
  // 如果重试失败，仍然设置为就绪状态，避免无限等待
  console.warn('组件准备就绪检查失败，强制设置为就绪状态')
  isReady.value = true
}

onMounted(async () => {
  await nextTick()
  await waitForReady()
})
</script>

<style scoped>
.safe-element-wrapper {
  width: 100%;
  height: 100%;
}

.safe-element-wrapper-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 100px;
  width: 100%;
}

.loading-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  color: #909399;
  font-size: 14px;
}

.loading-placeholder .el-icon {
  font-size: 20px;
}
</style> 